package com.zangs.emqx_expand.emqx.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {
    //算法名称
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES";

    public static void main(String[] args) throws Exception {
        System.out.println(decrypt("XKrCHvcwbCOvfJxwE7cjcc5ALnF9i0ElE05RlRJnT84=",encrypt("XKrCHvcwbCOvfJxwE7cjcc5ALnF9i0ElE05RlRJnT84=","asdafas")));
        System.out.println(encrypt("XKrCHvcwbCOvfJxwE7cjcc5ALnF9i0ElE05RlRJnT84=","asdafasasdafasasdafasasdafasasdafas"));
    }
    //加密
    public static String encrypt(String key,String data) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedData = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedData);
    }
    // 解密
    public static String decrypt(String key,String encryptedData) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedData);
    }



}
